<template>
  <div>
    <el-button type="primary" @click="visible = true">添加角色</el-button>

    <el-table :data="roleList" border>
      <el-table-column type="index" align="center" width="50" label="序号" />
      <el-table-column prop="roleName" label="角色名" />
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="primary"
            @click="$router.push(`/acl/role/auth/${row.id}`)"
          >
            分配菜单权限
          </el-button>
          <el-button type="danger" @click="removeRole(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="prev, pager, next, jumper, total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog title="添加角色" :visible.sync="visible">
      <el-form label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="roleName" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addRole">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      visible: false,
      roleName: ''
    }
  },
  mounted() {
    this.getRoleList()
  },
  methods: {
    async addRole() {
      await this.$API.acl.role.saveRole(this.roleName)
      this.$message.success('添加角色成功')
      this.getRoleList()
      this.cancel()
    },
    cancel() {
      this.roleName = ''
      this.visible = false
    },
    async removeRole(id) {
      await this.$API.acl.role.removeRole(id)
      this.$message.success('删除角色成功')
      this.getRoleList()
    },
    async getRoleList() {
      const { currentPage, pageSize } = this
      const result = await this.$API.acl.role.getRoleList(currentPage, pageSize)
      this.roleList = result.data.items
      this.total = result.data.total
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getRoleList()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getRoleList()
    }
  }
}
</script>

<style>
</style>
